# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import JsonResponse
from wetalk.models import Room, Message, Thumbsup

# Create your views here.
def room_list(request):
    data = []
    for room in Room.objects.all().order_by('id'):
        data.append({'id': room.id,
            'title': room.name,
            'members': room.get_members_count(),
            'comments': room.get_messages_count()})
    return JsonResponse({'code': 0, 'data': data})


def like_message(request):
    ip = request.META['HTTP_X_REAL_IP']
    message_id = request.POST['message_id']
    message = Message.objects.filter(id=message_id).first()
    if message == None:
        return JsonResponse({'code': 1, 'msg': u'message id not exists'})
    message.like(ip)
    data = {'id': message.id, 'like_count': message.likes, 'nickname': message.nickname, 'room_id': message.room_id}
    return JsonResponse({'code': 0, 'data': data})


def unlike_message(request):
    ip = request.META['HTTP_X_REAL_IP']
    message_id = request.POST['message_id']
    message = Message.objects.filter(id=message_id).first()
    if message == None:
        return JsonResponse({'code': 1, 'msg': u'message id not exists'})
    message.unlike(ip)
    data = {'id': message.id, 'like_count': message.likes, 'nickname': message.nickname, 'room_id': message.room_id}
    return JsonResponse({'code': 0, 'data': data})


def room_popular_messages(request):
    ip = request.META['HTTP_X_REAL_IP']
    room_id = request.POST['room_id']
    room = Room.objects.filter(id=room_id).first()
    if room == None:
        return JsonResponse({'code': 1, 'msg': u'room id not exists'})
    popular_messages = room.get_popular_messages()
    data = {'room_id': room.id, 'popular_messages': []}
    for msg in popular_messages:
        data['popular_messages'].append({'id': msg.id, 'nickname': msg.nickname, 
            'content': msg.content, 'like_count': msg.likes, 'is_liked': msg.is_liked(ip)})
    return JsonResponse({'code': 0, 'data': data})

